<script setup lang="ts">
import {useDictViewStore} from "@/store/views/sys/admin/dictStore";
import {FormInstance, FormRules} from "element-plus";
import {DictFormType} from "@/api/sys/admin/dict/types";
import {editDictApi} from "@/api/sys/admin/dict";
import {storeToRefs} from "pinia";
import {Perm} from "@/utils/enum-type";

const store = useDictViewStore()
const {setEditVisible, getList} = store
const {editVisible, editForm} = storeToRefs(store)


// 编辑表单时规则验证
const ruleFormRef = ref<FormInstance>()
const loading = ref(false)

const rules: FormRules<DictFormType> = ({
  name: [
    {required: true, message: '请输入名称', trigger: 'blur'},
    {min: 1, max: 20, message: '名称的长度为1-20', trigger: 'blur'},
  ],
  code: [
    {required: true, message: '请输入编码', trigger: 'blur'},
    {min: 1, message: '编码的名称不少于1个字符', trigger: 'blur'},
  ],
})


// 提交编辑
async function submitEdit(formEl: FormInstance | undefined) {
  if (!formEl) {
    return;
  }
  await formEl.validate((valid, fields) => {
    if (valid) {
      editDictApi(editForm.value.id!, editForm.value).then(async () => {
        loading.value = true
        await getList()
        ElMessage.success('修改成功')
        setEditVisible(false)
      }).finally(() => {
        loading.value = false
      })
    } else {
      console.log('错误的字段', fields)
    }
  })
}

</script>

<template>
  <!-- 弹出框 :编辑-->
  <el-dialog draggable v-model="editVisible" title="编辑字典" width="500" destroy-on-close>
    <el-form :model="editForm" label-suffix=":" label-width="90" ref="ruleFormRef" :rules="rules">
      <el-form-item label="名称" prop="name">
        <el-input v-model="editForm.name"/>
      </el-form-item>
      <el-form-item label="编码" prop="code">
        <el-input v-model="editForm.code"/>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="editForm.sort"/>
      </el-form-item>
      <el-form-item v-perm="Perm.SysDictStatus" label="状态" prop="status">
        <x-dict-select type-code="status" v-model="editForm.status"></x-dict-select>
      </el-form-item>
      <el-form-item label="描述" prop="remark">
        <el-input type="textarea" autosize v-model="editForm.remark"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="setEditVisible(false)">取消</el-button>
        <el-button type="primary" :loading="loading" @click="submitEdit(ruleFormRef)">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">

</style>